#include "facevideoitem.h"
#include <qdebug.h>
#include "cameravideobuffer.h"
#include <QCameraInfo>
#include <QCamera>
#include <QVideoFrame>
#include <QPainter>
#include <QSGSimpleTextureNode>
#include <QQuickWindow>
static void registerFaceVector()
{
    qRegisterMetaType< QVector<QRect> >("QVector<QRect>");
}

FaceVideoItem::FaceVideoItem(QQuickItem *parent)
    : QQuickItem(parent),mRunning(false)
{
    registerFaceVector();
    mpVideoBuffer=NULL;
    mpFaceAction=NULL;
    setFlag(ItemHasContents);
}
QSGNode * FaceVideoItem::updatePaintNode(QSGNode * oldNode, UpdatePaintNodeData * updatePaintNodeData)
{
    QSGSimpleTextureNode *n = static_cast<QSGSimpleTextureNode *>(oldNode);
    QVideoFrame currentFrame;
    if(mpVideoBuffer==NULL)
        return n;

    if(mpVideoBuffer->top(currentFrame)==false)
        return n;

    QImage image(currentFrame.bits(),currentFrame.width(), currentFrame.height(),currentFrame.bytesPerLine(),QImage::Format_RGB888);
    if (!n) {
        n = new QSGSimpleTextureNode();
        //n->setColor(Qt::red);
    }
    if(mFaces.size()>0)
    {
        QPen pen;
        QPainter painter(&image);
        pen.setWidth(3);
        painter.setPen(pen);
        painter.drawRect(mFaces[0]);
        painter.end();
    }

    n->setRect(boundingRect());
    QSGTexture* texture=window()->createTextureFromImage(image.scaled(boundingRect().size().toSize()));
    n->texture()->deleteLater();
    n->setTexture(texture);

    mpVideoBuffer->Pop();
    return n;
}

void FaceVideoItem::paint(QPainter *painter)
{
    qDebug()<<"paint";
    QVideoFrame currentFrame;
    if(NULL==mpVideoBuffer)
        return;

    if(mpVideoBuffer->top(currentFrame)==false)
        return;

    QImage image(currentFrame.bits(),currentFrame.width(), currentFrame.height(),currentFrame.bytesPerLine(),QImage::Format_RGB888);
    painter->drawImage(boundingRect(),image.mirrored(true,false));

    mpVideoBuffer->Pop();
}
void FaceVideoItem::UpdateFrame(QVideoFrame frame)
{
    //qDebug()<<"UpdateFrame";
    update();
}
